package cn.stylefeng.guns.modular.order.service.impl;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.order.entity.OrderWeightCheck;
import cn.stylefeng.guns.modular.order.mapper.OrderWeightCheckMapper;
import cn.stylefeng.guns.modular.order.model.params.OrderWeightCheckParam;
import cn.stylefeng.guns.modular.order.model.result.OrderWeightCheckResult;
import  cn.stylefeng.guns.modular.order.service.OrderWeightCheckService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * <p>
 * 订单重量复核 服务实现类
 * </p>
 *
 * @author zhangzh
 * @since 2024-05-20
 */
@Service
public class OrderWeightCheckServiceImpl extends ServiceImpl<OrderWeightCheckMapper, OrderWeightCheck> implements OrderWeightCheckService {

    @Override
    public void add(OrderWeightCheckParam param){
        OrderWeightCheck entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(OrderWeightCheckParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(OrderWeightCheckParam param){
        OrderWeightCheck oldEntity = getOldEntity(param);
        OrderWeightCheck newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public OrderWeightCheckResult findBySpec(OrderWeightCheckParam param){
        return this.baseMapper.findByOrderNo(param.getOrderNo());
    }

    @Override
    public List<OrderWeightCheckResult> findListBySpec(OrderWeightCheckParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(OrderWeightCheckParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 150)
    public ResponseData getExceldata(MultipartFile file, OrderWeightCheckParam orderWeightCheckParam, ResponseData data) throws Exception {
        String fileName = file.getOriginalFilename();

        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            data.setMessage("上传文件格式不正确");
            data.setSuccess(false);
        }

        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);

        List<OrderWeightCheckParam> list = new ArrayList<OrderWeightCheckParam>();
        OrderWeightCheckParam __orderWeightCheckParam = null;
        for (int r = 1; r <= sheet.getLastRowNum() + 1; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //实体类
            __orderWeightCheckParam = new OrderWeightCheckParam();
            //交付客户
            __orderWeightCheckParam.setDeliverId(orderWeightCheckParam.getDeliverId());
            //部门
            __orderWeightCheckParam.setDeptId(orderWeightCheckParam.getDeptId());
            //创建时间
            __orderWeightCheckParam.setCreateTime(orderWeightCheckParam.getCreateTime());
            //创建人
            __orderWeightCheckParam.setCreateUser(orderWeightCheckParam.getCreateUser());
            //修改人
            __orderWeightCheckParam.setUpdateUser(orderWeightCheckParam.getUpdateUser());

            String orderNo = getCellValue(row.getCell(0));
            if (ToolUtil.isNotEmpty(orderNo)) {
                __orderWeightCheckParam.setOrderNo(orderNo);
            }

            String weight = getCellValue(row.getCell(1));
            if (ToolUtil.isNotEmpty(weight)) {
                __orderWeightCheckParam.setWeight(Long.valueOf(weight));
            }
            //
            this.baseMapper.delByOrderNo(orderNo);
            list.add(__orderWeightCheckParam);
        }
        //批量保存
        this.baseMapper.saveBatchList(list);

        data.setSuccess(true);
        return data;
    }

    @Override
    public ResponseData updateCheckWeightByOrderNo(OrderWeightCheckParam orderWeightCheckParam) {
        this.baseMapper.updateCheckWeightByOrderNo(orderWeightCheckParam);
        ResponseData data = new ResponseData();
        data.setSuccess(true);
        return data;
    }

    private Serializable getKey(OrderWeightCheckParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private OrderWeightCheck getOldEntity(OrderWeightCheckParam param) {
        return this.getById(getKey(param));
    }

    private OrderWeightCheck getEntity(OrderWeightCheckParam param) {
        OrderWeightCheck entity = new OrderWeightCheck();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }


    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

}
